package edu.sdjzu.exam.service.exam.impl;



import cn.dev33.satoken.stp.StpUtil;

import edu.sdjzu.exam.domain.exam.Exam;
import edu.sdjzu.exam.domain.exam.ExamAssignment;
import edu.sdjzu.exam.domain.group.UserGroup;
import edu.sdjzu.exam.dto.ExamAssignmentCreateDTO;
import edu.sdjzu.exam.dto.ExamAssignmentDTO;
import edu.sdjzu.exam.dto.ExamAssignmentUpdateDTO;
import edu.sdjzu.exam.dto.ExamDTO;

import edu.sdjzu.exam.mapper.exam.ExamAssignmentMapper;
import edu.sdjzu.exam.mapper.exam.ExamMapper;
import edu.sdjzu.exam.mapper.group.UserGroupMapper;
import edu.sdjzu.exam.mapper.group.UserGroupMemberMapper;
import edu.sdjzu.exam.service.exam.ExamAssignmentService;
import edu.sdjzu.exam.service.exam.ExamService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ExamAssignmentServiceImpl implements ExamAssignmentService {

    private final ExamAssignmentMapper examAssignmentMapper;
    private final ExamMapper examMapper;
    private final UserGroupMapper userGroupMapper;
    private final UserGroupMemberMapper userGroupMemberMapper;
    private final ExamService examService;

    @Override
    @Transactional
    public Long createExamAssignment(ExamAssignmentCreateDTO createDTO) {
        // 验证试卷存在
        Exam exam = examMapper.selectExamById(createDTO.getExamId());
        if (exam == null) {
            throw new RuntimeException("试卷不存在");
        }
        // 验证用户组存在
        UserGroup userGroup = userGroupMapper.selectUserGroupById(createDTO.getGroupId());
        if (userGroup == null) {
            throw new RuntimeException("用户组不存在");
        }

        Long createdBy = StpUtil.getLoginIdAsLong();
        ExamAssignment assignment = new ExamAssignment();
        assignment.setExamId(createDTO.getExamId());
        assignment.setGroupId(createDTO.getGroupId());
        assignment.setStartTime(createDTO.getStartTime());
        assignment.setEndTime(createDTO.getEndTime());
        assignment.setCreatedBy(createdBy);

        examAssignmentMapper.insertExamAssignment(assignment);
        return assignment.getAssignmentId();
    }

    @Override
    public ExamAssignmentDTO getExamAssignment(Long assignmentId) {
        ExamAssignment assignment = examAssignmentMapper.selectExamAssignmentById(assignmentId);
        if (assignment == null) {
            throw new RuntimeException("考试安排不存在");
        }

        ExamDTO examDTO = examService.getExam(assignment.getExamId());
        UserGroup userGroup = userGroupMapper.selectUserGroupById(assignment.getGroupId());

        ExamAssignmentDTO dto = new ExamAssignmentDTO();
        dto.setAssignmentId(assignment.getAssignmentId());
        dto.setExamId(assignment.getExamId());
        dto.setGroupId(assignment.getGroupId());
        dto.setStartTime(assignment.getStartTime());
        dto.setEndTime(assignment.getEndTime());
        dto.setCreatedBy(assignment.getCreatedBy());
        dto.setCreatedAt(assignment.getCreatedAt());
        dto.setUpdatedAt(assignment.getUpdatedAt());
        dto.setExam(examDTO);
        dto.setGroupName(userGroup != null ? userGroup.getGroupName() : null);

        return dto;
    }

    @Override
    @Transactional
    public void updateExamAssignment(ExamAssignmentUpdateDTO updateDTO) {
        ExamAssignment assignment = examAssignmentMapper.selectExamAssignmentById(updateDTO.getAssignmentId());
        if (assignment == null) {
            throw new RuntimeException("考试安排不存在");
        }
        // 验证试卷存在
        Exam exam = examMapper.selectExamById(updateDTO.getExamId());
        if (exam == null) {
            throw new RuntimeException("试卷不存在");
        }
        // 验证用户组存在
        UserGroup userGroup = userGroupMapper.selectUserGroupById(updateDTO.getGroupId());
        if (userGroup == null) {
            throw new RuntimeException("用户组不存在");
        }

        assignment.setExamId(updateDTO.getExamId());
        assignment.setGroupId(updateDTO.getGroupId());
        assignment.setStartTime(updateDTO.getStartTime());
        assignment.setEndTime(updateDTO.getEndTime());
        examAssignmentMapper.updateExamAssignment(assignment);
    }

    @Override
    @Transactional
    public void deleteExamAssignment(Long assignmentId) {
        ExamAssignment assignment = examAssignmentMapper.selectExamAssignmentById(assignmentId);
        if (assignment == null) {
            throw new RuntimeException("考试安排不存在");
        }
        examAssignmentMapper.deleteExamAssignment(assignmentId);
    }

    @Override
    public List<ExamAssignmentDTO> listExamAssignmentsByCreator() {
        Long createdBy = StpUtil.getLoginIdAsLong();
        List<ExamAssignment> assignments = examAssignmentMapper.selectExamAssignmentsByCreator(createdBy);
        return assignments.stream().map(assignment -> {
            ExamDTO examDTO = examService.getExam(assignment.getExamId());
            UserGroup userGroup = userGroupMapper.selectUserGroupById(assignment.getGroupId());

            ExamAssignmentDTO dto = new ExamAssignmentDTO();
            dto.setAssignmentId(assignment.getAssignmentId());
            dto.setExamId(assignment.getExamId());
            dto.setGroupId(assignment.getGroupId());
            dto.setStartTime(assignment.getStartTime());
            dto.setEndTime(assignment.getEndTime());
            dto.setCreatedBy(assignment.getCreatedBy());
            dto.setCreatedAt(assignment.getCreatedAt());
            dto.setUpdatedAt(assignment.getUpdatedAt());
            dto.setExam(examDTO);
            dto.setGroupName(userGroup != null ? userGroup.getGroupName() : null);

            return dto;
        }).filter(dto -> dto != null) // 过滤掉null值（考试不存在的情况）
        .collect(Collectors.toList());
    }

    @Override
    public List<ExamAssignmentDTO> listMyExamAssignments() {
        Long userId = StpUtil.getLoginIdAsLong();
        List<String> roles = StpUtil.getRoleList();
        
        List<ExamAssignment> assignments;
        
        if (roles.contains("teacher")) {
            // 教师：返回自己创建的考试安排
            assignments = examAssignmentMapper.selectExamAssignmentsByCreator(userId);
        } else if (roles.contains("student")) {
            // 学生：返回自己可以参加的考试安排
            assignments = examAssignmentMapper.selectExamAssignmentsByStudent(userId);
        } else {
            throw new RuntimeException("无效的用户角色");
        }
        
        return assignments.stream().map(assignment -> {
            ExamDTO examDTO;
            if (roles.contains("teacher")) {
                // 教师可以获取完整的考试信息（包含题目详情）
                try {
                    examDTO = examService.getExam(assignment.getExamId());
                } catch (Exception e) {
                    // 如果考试不存在，跳过这个考试安排
                    return null;
                }
            } else {
                // 学生获取考试信息，包含题目详情和总分
                try {
                    examDTO = examService.getExam(assignment.getExamId());
                } catch (Exception e) {
                    // 如果考试不存在，跳过这个考试安排
                    return null;
                }
            }
            
            UserGroup userGroup = userGroupMapper.selectUserGroupById(assignment.getGroupId());

            ExamAssignmentDTO dto = new ExamAssignmentDTO();
            dto.setAssignmentId(assignment.getAssignmentId());
            dto.setExamId(assignment.getExamId());
            dto.setGroupId(assignment.getGroupId());
            dto.setStartTime(assignment.getStartTime());
            dto.setEndTime(assignment.getEndTime());
            dto.setCreatedBy(assignment.getCreatedBy());
            dto.setCreatedAt(assignment.getCreatedAt());
            dto.setUpdatedAt(assignment.getUpdatedAt());
            dto.setExam(examDTO);
            dto.setGroupName(userGroup != null ? userGroup.getGroupName() : null);

            return dto;
        }).collect(Collectors.toList());
    }
}
